<template>
    <div class="flex items-center ml-26px mr-26px mt-20px mb-20px friendly-tips">
        <svg-icon size="18px"
            icon-class="information-2-fill"></svg-icon>友情提示：用户可以自由填写关键词，但自定义关键词中必须包含主关键词，且不能与已有组合关键词（前置+主关键词+后置）重复。为了保证产品的精准推广，自定义关键词仅限填写<el-text
            type="danger">30</el-text>个。
    </div>
    <div class="pl-26px" v-for="(item, idx) in cusKeyWords" :key="idx">
        <el-form>
            <el-form-item>
                <div class="flex">
                    <el-input :id="'customKey-'+idx" v-model="cusKeyWords[idx]" :key="idx" placeholder="请输入关键词" class="w-300px mr-20px cus-key-input"></el-input>
                    <el-button v-if="idx > 0" type="danger" :icon="Delete" circle @click="handleDeleteCusKey(idx)" />
                    <el-button type="primary" :icon="Plus" circle @click="handleAddCusKey()" />
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue'

const props = defineProps<{
    ruleForm: any
}>()

//自定义关键词
const cusKeyWords = ref<string[]>([])

// 初始化
watchEffect(() => {
    cusKeyWords.value = props.ruleForm.cusKeyword.split('/')
})

// 同步回 ruleForm.cusKeyword
watch(cusKeyWords, (newVal) => {
    props.ruleForm.cusKeyword = newVal.filter(Boolean).join('/')
}, { deep: true })
function handleAddCusKey() {
    // 限制最多添加 30 个关键词
    if (cusKeyWords.value.length >= 30) {
        ElMessage.warning('最多只能添加 30 个关键词')
        return
    }

    // 添加一个空字符串作为新关键词
    cusKeyWords.value.push('')

    nextTick(() => {
        //新增并获取焦点
        const id = cusKeyWords.value.length-1
        const elementId = 'customKey-' + id;
        const element = document.getElementById(elementId);
        if (element) {
            element.focus();
        }
    })
}

function handleDeleteCusKey(index: number) {
    if (cusKeyWords.value.length <= 1) {
        ElMessage.warning('至少保留一个关键词')
        return
    }

    if (index >= 0 && index < cusKeyWords.value.length) {
        cusKeyWords.value.splice(index, 1)
    }
}
</script>

<style scoped>

</style>